//
// @Auther: by wujehy 
// @Email:wujehy@qq.com
// @Data:20-2-14
// @Time:下午7:00
//

#include "E2EEFactory.h"

#include <cstring>
#include "Common.h"


using namespace GeeJoan::E2EE::Common;
using namespace GeeJoan::E2EE::SDK;

void E2EEFactory::setMIdk(const KeyPairDataType &mIdk)
{
    deserializationEcKeyPair((KeyPairDataType &) mIdk, &m_idk, this->m_global_context);
}

void E2EEFactory::setMSpk(const KeyPairDataType &mSpk)
{
    deserializationEcKeyPair((KeyPairDataType &) mSpk, &m_spk, this->m_global_context);
}


int E2EEFactory::creatIDK()
{
    KeyPairDataType temp;
    creatEcKeyPack(temp, m_global_context);
    setMIdk(temp);
    return 0;
}

int E2EEFactory::creatSPK()
{
    KeyPairDataType temp;
    creatEcKeyPack(temp, m_global_context);

    setMSpk(temp);
}


E2EEFactory::E2EEFactory()
{
    pthread_mutexattr_init(&global_mutex_attr);
    pthread_mutexattr_settype(&global_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
    pthread_mutex_init(&global_mutex, &global_mutex_attr);
    int result;
    // 创建全局变量
    result = signal_context_create(&m_global_context, nullptr);

    // 设置 函数器
    E2EE::Common::common_setup_crypto_provider(m_global_context, nullptr);

    e2EeopkManager = std::unique_ptr<OPKManager>(new OPKManager(m_global_context));
}

E2EEFactory::~E2EEFactory()
{
    //拆卸
    pthread_mutex_destroy(&global_mutex);
    pthread_mutexattr_destroy(&global_mutex_attr);
    if (m_spk)
    {
        std::cout << " delete m_spk " << std::endl;
        ec_key_pair_destroy((signal_type_base *) m_spk);
    }

    if (m_idk)
    {
        std::cout << " delete m_ik" << std::endl;
        ratchet_identity_key_pair_destroy((signal_type_base *) m_idk);
    }

    if (m_global_context)
    {
        signal_context_destroy(m_global_context);
    }
}

KeyPairDataType E2EEFactory::getMIdk()
{
    KeyPairDataType keyPairData;
    serialEcKeyPair(m_idk, keyPairData);
    return keyPairData;
}

KeyPairDataType E2EEFactory::getMSpk()
{
    KeyPairDataType keyPairData;
    serialEcKeyPair(m_spk, keyPairData);
    return keyPairData;
}

KeyPairDataType E2EEFactory::getMOpk()
{
    return *e2EeopkManager->getAKeyPair();
}

const std::unique_ptr<OPKManager> &E2EEFactory::getOpkManager() const
{
    return e2EeopkManager;
}

